package cn.hlife.com.hlfhaemocyte.view;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Path;
import android.graphics.Path.Direction;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.graphics.Region;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.FrameLayout;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.hlife.com.hlfhaemocyte.R;
import cn.hlife.com.hlfhaemocyte.utils.DisplayUtil;
import cn.hlife.com.hlfhaemocyte.utils.HaemocyteApplication;

/**
 * 水波浪球形进度View
 * 
 * @author caizhiming
 * 
 */
public class WaterWaveView extends FrameLayout {
	private static final int DEFAULT_TEXTCOLOT = 0xFFFFFFFF;

	private final Paint arcLinePaint;
	private final int valueB;
	private final int paintWidth;
	private final Paint wavePaint;

	private float mPercent;



	private Bitmap mBitmap;

	private Bitmap mScaledBitmap;

	private float mLeft;

	private int mSpeed = 5;

	private int mRepeatCount = 0;

	private Status mFlag = Status.NONE;

	private int mTextColor = DEFAULT_TEXTCOLOT;

	private int mTextSize;

	private ExecutorService threadPool;

	private float currentPercent;
	private String str;
	private final Paint mPaint;
	private final PaintFlagsDrawFilter mSetfil;
	private int paintWidth_2;
	private final PorterDuffXfermode xfermode;
	private int heightValue= DisplayUtil.dip2px(HaemocyteApplication.getInstance(),15);
	private final Typeface typeFace;

	public WaterWaveView(Context context, AttributeSet attrs) {
		super(context, attrs);

		AssetManager assetManager = context.getAssets();
		typeFace = Typeface.createFromAsset(assetManager, "fonts/HelveticaNeue-Thin.ttf");

		mSetfil = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG| Paint.FILTER_BITMAP_FLAG| Paint.DITHER_FLAG);
		xfermode = new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY);
		mPaint = new Paint();
		mPaint.setDither(true);
		mPaint.setAntiAlias(true);

		paintWidth = DisplayUtil.dip2px(context, 4);
		paintWidth_2 = DisplayUtil.dip2px(context, 1);
		valueB = DisplayUtil.dip2px(context, 1);
		mTextSize = DisplayUtil.dip2px(context, 15);

		arcLinePaint = new Paint();
		arcLinePaint.setStrokeWidth(paintWidth);
		arcLinePaint.setStyle(Style.STROKE);
		arcLinePaint.setDither(true);
		arcLinePaint.setColor(0xFFe4e3e8);

		threadPool = Executors.newSingleThreadExecutor();

		wavePaint =new Paint();
		wavePaint.setDither(true);
		wavePaint.setAntiAlias(true);
		wavePaint.setStyle(Style.FILL);


	}

	public void stopViewDraw(){
		if(null!=threadPool)
			threadPool.shutdownNow();
	}


	public void setTextColor(int color) {
		mTextColor = color;
	}

	public void setTextSize(int size) {
		mTextSize = size;
	}

	public void setPercent(final int percent) {

		mFlag = Status.RUNNING;
		mPercent = percent;
		threadPool.execute(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (currentPercent <percent) {

					currentPercent +=1;
					if(heightValue>0) {
						heightValue--;
					}
					postInvalidate();
					try {
						Thread.sleep(60);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

				}
				// clear();
			}
		});

	}

	public void setStatus(Status status) {
		mFlag = status;
	}

	public void clear() {
		mFlag = Status.NONE;
		if (mScaledBitmap != null) {
			mScaledBitmap.recycle();
			mScaledBitmap = null;
		}

		if (mBitmap != null) {
			mBitmap.recycle();
			mBitmap = null;
		}
	}

	@Override
	protected void dispatchDraw(Canvas canvas) {
		super.dispatchDraw(canvas);

//		canvas.setDrawFilter(mSetfil);
		int width = getWidth();
		int height = getHeight();

		int centerX=width/2;
		int centerY=height/2;
		// 裁剪成圆区域
		Path path = new Path();

		int radius=(int)(width/2*0.85);

		RectF ovallF = new RectF(centerX-radius, centerY-radius,
				centerX+radius, centerY+radius);

		mPaint.setColor(0xFFB8DBF4);
		mPaint.setStyle(Style.FILL);
		canvas.drawCircle(centerX, centerY, radius, mPaint);


//		canvas.save();
		path.reset();
//		path.close();
//		canvas.clipPath(path);
//

		path.addCircle(centerX, centerY, radius, Direction.CCW);
		canvas.clipPath(path, Region.Op.REPLACE);
		canvas.setDrawFilter(mSetfil);

		if (mFlag == Status.RUNNING) {
			if (mScaledBitmap == null) {
				mBitmap = BitmapFactory.decodeResource(getContext()
						.getResources(), R.drawable.wave);
				mScaledBitmap = Bitmap.createScaledBitmap(mBitmap,
						mBitmap.getWidth(), getHeight(), false);
				mBitmap.recycle();
				mBitmap = null;
				mRepeatCount = (int) Math.ceil(getWidth()
						/ mScaledBitmap.getWidth() + 0.5)+1 ;
			}
//			if(0.20>currentPercent){
				for (int idx = 0; idx < mRepeatCount; idx++) {
					canvas.drawBitmap(mScaledBitmap, mLeft + (idx - 1)
							* mScaledBitmap.getWidth(), (1 - (currentPercent/100))
							* getHeight()-heightValue, wavePaint);
				}
//			}else {
//				for (int idx = 0; idx < mRepeatCount; idx++) {
//					canvas.drawBitmap(mScaledBitmap, mLeft + (idx - 1)
//							* mScaledBitmap.getWidth(), (1 - currentPercent)
//							* getHeight(), wavePaint);
//				}
//			}

			if (0 != mPercent) {
				str = (int) currentPercent + "%";
			} else {
				str = 0 + "%";
			}
			mPaint.setColor(mTextColor);
			mPaint.setTextSize(mTextSize);
			mPaint.setStyle(Style.FILL);
			mPaint.setTypeface(typeFace);
			canvas.drawText(str, (getWidth() - mPaint.measureText(str)) / 2,
					getHeight() / 2 + mTextSize / 2-valueB, mPaint);

			mLeft += mSpeed;
			if (mLeft >= mScaledBitmap.getWidth())
				mLeft = 0;
			// 绘制外圆环
			mPaint.setStyle(Style.STROKE);
			mPaint.setStrokeWidth(paintWidth_2);
			mPaint.setColor(0xFF5DB5F2);
			canvas.drawCircle(centerX, centerY, radius-2, mPaint);
			canvas.drawArc(ovallF, 0, 360, false, arcLinePaint);
			postInvalidateDelayed(100);
		}
//		canvas.restore();

	}

	public enum Status {
		RUNNING, NONE
	}

}
